package com.yunshipei.ui.fragment;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.google.zxing.activity.CaptureActivity;
import com.yunshipei.common.Globals;
import com.yunshipei.common.KingGrid;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.core.manager.TabManager;
import com.yunshipei.core.model.AutoLoginModel;
import com.yunshipei.core.model.CookieModel;
import com.yunshipei.core.model.DeveloperAppModel;
import com.yunshipei.core.model.FilePreviewConfig;
import com.yunshipei.core.model.HttpAuthModel;
import com.yunshipei.core.model.RequestHeaderSSOModel;
import com.yunshipei.core.model.UrlTokenSSOModel;
import com.yunshipei.core.model.WaterMarkConfig;
import com.yunshipei.core.ui.TabFragment;
import com.yunshipei.core.utils.CommonUtils;
import com.yunshipei.core.utils.NetUtils;
import com.yunshipei.db.green.XCloudSign;
import com.yunshipei.db.green.XCloudSignDao;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.EnterDbManager;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.CheckInJSModel;
import com.yunshipei.model.CollectionItemData;
import com.yunshipei.model.Company;
import com.yunshipei.model.HomeAppsBean;
import com.yunshipei.model.MainExtraBean;
import com.yunshipei.model.ManagedSingleSignOn;
import com.yunshipei.model.PointModel;
import com.yunshipei.model.SSOSModel;
import com.yunshipei.model.ShareInfoModel;
import com.yunshipei.model.UserInfo;
import com.yunshipei.model.VPNInfo;
import com.yunshipei.model.WaterMarkSettings;
import com.yunshipei.model.XPs;
import com.yunshipei.model.YspEvent;
import com.yunshipei.model.YspEvent.TabChangeEvent;
import com.yunshipei.ui.activity.MultiActivity;
import com.yunshipei.ui.activity.NoContactsSettingsActivity;
import com.yunshipei.ui.activity.ShareActivity;
import com.yunshipei.ui.dialog.DialogHelper;
import com.yunshipei.ui.dialog.WaitDialog;
import com.yunshipei.utils.BaseUtil;
import com.yunshipei.utils.EncUtils;
import com.yunshipei.utils.FileUtils;
import com.yunshipei.utils.LogHandlerUtils;
import com.yunshipei.utils.ToastUtils;
import com.yunshipei.utils.encryption.Aes;
import com.yunshipei.wps.WPSManager;

import org.chromiun.net.ProxyChangeListener;
import org.json.JSONException;
import org.json.JSONObject;
import org.reactivestreams.Publisher;
import org.xwalk.core.XWalkHttpAuthHandler;
import org.xwalk.core.XWalkView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import io.rong.eventbus.EventBus;

import static com.google.zxing.activity.CaptureActivity.INTENT_QR_SCAN_RESULT;
import static com.google.zxing.activity.CaptureActivity.INTENT_QR_SCAN_SERVICE;
import static com.yunshipei.core.model.FilePreviewConfig.TYPE_MOBILE_DOWNLOAD_PREVIEW;
import static com.yunshipei.core.model.FilePreviewConfig.TYPE_ONLINE_PREVIEW;

public class BrowserFragment extends Fragment implements TabFragment.OnFragmentInteractionListener, TextSizeSettingFragment.OnFragmentInteractionListener, MenuFragment.OnFragmentInteractionListener {

    private static final int REQUEST_CODE_SEND_IMAGE = 300;
    private static final String ARGS_BROWSER_DATA = "com.enterplorer.browser.data";
    private static final String DOC_CONVERT_SERVER_URL = "http://139.217.22.35:8080";

    @Bind(R.id.fl_menu_more)
    protected View mMenuView;
    @Bind(R.id.tab_progress_bar)
    protected ProgressBar mProgressBar;
    @Bind(R.id.rl_font_size_view_container)
    protected RelativeLayout mFontSizeChangeViewContainer;

    private Context mContext;
    private TabManager mTabManager;
    private MainExtraBean mMainExtraBean;
    private Map<String, XPs> mXPsMap = new HashMap<>();
    private MenuFragment mMenuFragment;
    private BrowserInteractionListener mInteractionListener;
    private boolean isUseContacts = true;
    private String mUserName;
    private String mPassword;

    private WaitDialog mLoading;
    private static final int REQUEST_CODE_SCAN = 523;

    public static BrowserFragment newInstances(MainExtraBean mainExtraBean) {
        BrowserFragment browserFragment = new BrowserFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ARGS_BROWSER_DATA, mainExtraBean);
        browserFragment.setArguments(bundle);
        return browserFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof BrowserInteractionListener) {
            mInteractionListener = (BrowserInteractionListener) context;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        this.mContext = getActivity();
        this.mMainExtraBean = (MainExtraBean) getArguments().getSerializable(ARGS_BROWSER_DATA);
        this.isUseContacts = mMainExtraBean == null || mMainExtraBean.isUseContacts();
        if (mMainExtraBean != null) {
            List<SSOSModel> ssoModels = mMainExtraBean.getSsosModels();
            if (ssoModels != null) {
                for (SSOSModel ssosModel : ssoModels) {
                    int type = ssosModel.type;
                    if (type == 1) continue;
                    String host = CommonUtils.getHost(ssosModel.address);
                    Log.e("ssosModel",host);
                    Log.e("ssosModelpasswordXPath",ssosModel.passwordXPath);

                    if (TextUtils.isEmpty(host)) continue;
                    mXPsMap.put(host, new XPs(ssosModel.userNameXPath, ssosModel.passwordXPath, ssosModel.certXPath, ssosModel.loginBtnXPath));
                }
            }
        }
        this.mTabManager = TabManager.getInstance();
        SharedPreferences preferences = YspPreferences.getInstance().getSharedPreferences();
        this.mUserName = preferences.getString(Globals.USER_NAME, "");
        String encPassword = preferences.getString(Globals.PASSWORD, "");
        this.mPassword = EncUtils.decrypt(mMainExtraBean.getUserInfo().getUuid(), encPassword);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_yunshipei_main, container, false);
        ButterKnife.bind(this, view);


        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        FragmentManager fragmentManager = getChildFragmentManager();
        Fragment fragment = fragmentManager.findFragmentByTag(MenuFragment.class.getName());
        if (fragment == null) {
            UserInfo userInfo = mMainExtraBean.getUserInfo();
            //2018/8/9 替换name值
            String userName = YspPreferences.getInstance().getSharedPreferences().getString("ADUserName","");
            String userImage = userInfo.getAvatar();
            mMenuFragment = MenuFragment.newInstance(userName, userImage);
            fragmentManager.beginTransaction().replace(R.id.fl_menu_more, mMenuFragment, MenuFragment.class.getName()).commit();
        } else {
            mMenuFragment = (MenuFragment) fragment;
        }
    }

    //===========菜单点击事件 start=============
    @Override
    public void goFroward() {
        if (mTabManager.getSize() == 0) {
            showHomePage();
        } else {
            getCurrentFragment().forward();
        }
    }

    @Override
    public void goBack() {
        Log.e("onBack",YspPreferences.getInstance().getSharedPreferences().getString("closePageType",""));
        if (YspPreferences.getInstance().getSharedPreferences().getString("closePageType","").equals("1")) {
            TabManager.getInstance().removeAllViews();
            showHomePage();
            EventBus.getDefault().post(new TabChangeEvent(0));
            YspPreferences.getInstance().getSharedPreferences().edit().putString("closePageType","0").apply();
        } else {
            if (YspPreferences.getInstance().getSharedPreferences().getString("closePageType","").equals("2")){
                YspPreferences.getInstance().getSharedPreferences().edit().putString("closePageType","1").apply();

            }
             browserBack();
        }
    }

    @Override
    public void refresh() {
        TabFragment currentTab = getCurrentFragment();
        if (currentTab != null) {
            currentTab.refresh();
        }
    }

    @Override
    public void home() {
        Log.e("ddd",1+"");
        showHomePage();
        EventBus.getDefault().post(new TabChangeEvent(0));
    }

    @Override
    public void message() {
        showHomePage();
        EventBus.getDefault().post(new TabChangeEvent(1));
    }



    @Override
    public void openPC() {
        TabFragment tabFragment = getCurrentFragment();
        if (tabFragment != null) {
            tabFragment.openPCPage();
        }
    }

    @Override
    public void settings() {
        if (isUseContacts) {
            startActivity(new MultiActivity.MultiActivityIntentBuilder(getActivity()).setMainData(mMainExtraBean).setTargetPartClazzName(SettingsFragment.class.getName()).getIntent());
        } else {
            startActivity(new NoContactsSettingsActivity.NoContactsSettingIntentBuilder(mContext).setMainExtra(mMainExtraBean).getIntent());
        }
    }

    @Override
    public void share(View view) {
        if (NetUtils.isNetworkAvailable(mContext)) {
            ShareInfoModel shareInfoModel = getShareInfo();
            if (shareInfoModel != null) {
                Bundle bundle = new Bundle();
                bundle.putSerializable(Globals.SHARE_TARGET, shareInfoModel);
                Intent intent = new Intent(mContext, ShareActivity.class);
                intent.putExtra(Globals.SHARE_TARGET, bundle);
                startActivity(intent);
            }
        } else {
            ToastUtils.showToast(R.string.net_unavailable);
        }
    }

    //开启浏览器的更多菜单之后，更新UI的状态
    @Override
    public void onMoreMenuHide(boolean hide) {
        boolean enableShare = false;
        boolean canOpenPC = false;
        if (!hide) {
            TabFragment tabFragment = getCurrentFragment();
            if (tabFragment != null) {
                canOpenPC = tabFragment.isCurrentPageSupportOpenPC();
                enableShare = !tabFragment.isCurrentYspWebApp();
            }
        }
        if (!isUseContacts) {
            enableShare = false;
        }
        mMenuFragment.setShareBtnEnable(enableShare);
        mMenuFragment.setOpenPCBtnEnable(canOpenPC);
    }

    @Override
    public void showFontSizeSetting() {
        FragmentManager fm = getChildFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        TextSizeSettingFragment textSizeSettingFragment = (TextSizeSettingFragment) fm.findFragmentByTag(TextSizeSettingFragment.class.getName());
        int position = YspPreferences.getInstance().getSharedPreferences().getInt(Globals.WEB_VIEW_TEXT_ZOOM, 1);
        if (textSizeSettingFragment == null) {
            textSizeSettingFragment = TextSizeSettingFragment.newInstance(position);
            ft.add(R.id.fl_font_size_container, textSizeSettingFragment, TextSizeSettingFragment.class.getName()).commit();
        } else {
            textSizeSettingFragment.setDefaultFontZoomPosition(position);
        }
        mFontSizeChangeViewContainer.setVisibility(View.VISIBLE);
    }
    //===========菜单点击事件 end=============

    @OnClick({R.id.view_font_size_settings_bg})
    protected void onClickEvent() {
        mFontSizeChangeViewContainer.setVisibility(View.INVISIBLE);
    }

    //修改字体大小
    public void onEventMainThread(YspEvent.BrowserFontSizeChange fontSizeChange) {
        changeWebSize(fontSizeChange.getPosition());
    }

    //下拉刷新更新HomeApps数据
    public void onEventMainThread(YspEvent.UpdateHomeApps updateHomeApps) {
        if (mMainExtraBean != null) {
            mMainExtraBean.setHomeApps(updateHomeApps.getHomeApps());
            //更新每个Tab的menu
            int size = mTabManager.getSize();
            for (int i = 0; i < size; i++) {
                TabFragment tabFragment = mTabManager.getFragment(i);
                if (tabFragment != null) {
                    String url = tabFragment.getStartURL();
                    tabFragment.updateMenu(optAppMenu(url));
                }
            }
        }
    }

    //头像更换通知
    public void onEventMainThread(YspEvent.UserAvatarChangedEvent event) {
        mMenuFragment.updateUserImage(event.getData());
    }

    //更新未读消息数目
    public void onEventMainThread(YspEvent.MessageNumEvent event) {
        mMenuFragment.updateUnreadMsgNum(event.getNum());
    }

    @Override
    public void changeWebSize(int position) {
        int size = BaseUtil.parseTextZoomSize(position);
        YspPreferences.getInstance().getSharedPreferences().edit().putInt(Globals.WEB_VIEW_TEXT_ZOOM, position).apply();
        for (int i = 0; i < mTabManager.getSize(); i++) {
            TabFragment tabFragment = mTabManager.getFragment(i);
            if (tabFragment != null) {
                tabFragment.changeWebDefaultFontSize(size);
            }
        }
    }

    //获取分享信息
    private ShareInfoModel getShareInfo() {
        TabFragment tabFragment = getCurrentFragment();
        if (tabFragment != null) {
            String url = tabFragment.getURLFromAddrBar();
            if (!TextUtils.isEmpty(url)) {
                ShareInfoModel shareInfoModel = new ShareInfoModel();
                shareInfoModel.setUrl(url);
                shareInfoModel.setHtmlTitle(getTopWebViewTitle(tabFragment));
                shareInfoModel.setImageUri(tabFragment.getTabAvatarName(true));
                return shareInfoModel;
            }
        }
        return null;
    }

    //当前WebView的标题，适配应用通过WebView拿不到title，测试要求是九宫格某个app的标题
    private String getTopWebViewTitle(TabFragment tabFragment) {
        String title = "无标题";
        List<HomeAppsBean> mHomeApps = mMainExtraBean.getHomeApps();
        if (!tabFragment.isTopWebViewAdapter()) {
            title = tabFragment.getTopItemWebViewTitle();
        } else if (mHomeApps != null) {
            String mUrl = tabFragment.getTopItemOriginUrl();
            String appId = CommonUtils.getUrlParams(mUrl, Globals.WEB_APP_ID);
            if (!TextUtils.isEmpty(appId)) {
                for (HomeAppsBean homeAppsBean : mHomeApps) {
                    if (appId.equals(homeAppsBean.getAppId())) {
                        title = homeAppsBean.getAppName();
                        break;
                    }
                }
            } else {
                String appParentId = CommonUtils.getUrlParams(tabFragment.getStartURL(), Globals.WEB_APP_ID);
                if (!TextUtils.isEmpty(appParentId)) {
                    for (HomeAppsBean homeAppsBean : mHomeApps) {
                        if (appParentId.equals(homeAppsBean.getAppId())) {
                            List<HomeAppsBean> childApps = homeAppsBean.getHomeAppsBeans();
                            if (childApps != null) {
                                for (HomeAppsBean childHomeApp : childApps) {
                                    if (mUrl.equals(childHomeApp.getAppURL())) {
                                        title = childHomeApp.getAppName();
                                        break;
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
            }

        }
        return title;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mInteractionListener = null;
    }

    //======================================start：浏览器文件处理逻辑，下载与预览以及金格的下载与预览==============================================

    private BroadcastReceiver mDocFileSaveReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            context.unregisterReceiver(mDocFileSaveReceiver);
            String fileName = intent.getExtras().getString("CurrentPath");
            uploadKingGridFile(fileName);
        }
    };

    private String mKingGridData = "";
    private int mKingGridUploadProxyPort = 0;
    private String mKingGridUploadProxyIP = "";

    //金格文件操作完毕，保存后上传
    private void uploadKingGridFile(String fileName) {
        showLoading("正在保存文件,请稍候...");
        new KingGrid(mKingGridData, mKingGridUploadProxyIP, mKingGridUploadProxyPort).kingGridUploadFlowable(fileName, "").subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                hideLoading();
                ToastUtils.showToast("文件上传完成...");
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                hideLoading();
                ToastUtils.showToast(throwable.toString());
            }
        });
    }

    @Override
    public void kingGridFile(final String data) {
        showLoading("下载中,请稍候...");
        ProxyChangeListener.ProxyConfig proxyConfig = ProxyChangeListener.getProxyConfig();
        String proxyIP = "";
        int proxyPort = 0;
        if (proxyConfig != null) {
            proxyIP = proxyConfig.mHost;
            proxyPort = proxyConfig.mPort;
        }
        final WPSManager wpsManager = WPSManager.getInstance().init(mContext);
        final String finalProxyIP = proxyIP;
        final int finalProxyPort = proxyPort;
        new KingGrid(data, proxyIP, proxyPort).kingGridFileDownloadFlowable().subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String fileName) throws Exception {
                hideLoading();
                mKingGridData = data;
                mKingGridUploadProxyIP = finalProxyIP;
                mKingGridUploadProxyPort = finalProxyPort;
                mContext.registerReceiver(mDocFileSaveReceiver, new IntentFilter("cn.wps.moffice.broadcast.AfterSaved"));
                wpsManager.openFile(fileName, mContext);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                hideLoading();
                ToastUtils.showToast(throwable.toString());
            }
        });
    }
    //======================================end：浏览器文件处理逻辑，下载与预览以及金格的下载与预览==============================================

    private void showLoading(String message) {
        if (mLoading == null) {
            mLoading = DialogHelper.getNoCancelableWaitDialog(mContext, message);
        } else {
            mLoading.setMessage(message);
        }
        if (!mLoading.isShowing()) {
            mLoading.show();
        }
    }

    private void hideLoading() {
        if (mLoading != null && mLoading.isShowing()) {
            mLoading.dismiss();
        }
    }

    /**
     * 将TabFragment对象attach到activity中
     *
     * @param tabFragment 要attach的Fragment
     * @param fromTabs    标记该tab是否是从TabManager中拿到的，如果是新创建的则返回false，否则从TabManager中拿到的则返回true
     */
    private void attachTabFragment(TabFragment tabFragment, boolean fromTabs) {

        if (fromTabs) {
            configProxy(tabFragment.getStartURL());
        }
        FragmentManager fm = getChildFragmentManager();
        fm.beginTransaction()
                .replace(R.id.fl_browser_content, tabFragment, TabFragment.class.getName()).addToBackStack(null).commit();
        fm.executePendingTransactions();
        statisticApp(tabFragment);
    }

    //内核这种设置代理的方法可能不生效，所以在外面调用一下，可以解决内核某些情况下代理不生效的问题
    private void configProxy(String startURL) {
        VPNInfo mCurrentVPN = null;
        String host = CommonUtils.getHost(startURL);
        if (!TextUtils.isEmpty(host)) {
            List<VPNInfo> vpnInfos = mMainExtraBean.getVpnInfos();
            if (vpnInfos != null && vpnInfos.size() > 0) {
                for (VPNInfo tempVPN : vpnInfos) {
                    if ("yspvpn".equals(tempVPN.getVpnType()) && tempVPN.getHosts().contains(host)) {
                        mCurrentVPN = tempVPN;
                        break;
                    }
                }
            }
        }
        String ip = null;
        int port = -1;
        String[] pacArray = null;
        if (mCurrentVPN != null) {
            ip = mCurrentVPN.getVpnAddress();
            port = mCurrentVPN.getVpnPort();
            List<String> hosts = mCurrentVPN.getHosts();
            pacArray = hosts.toArray(new String[hosts.size()]);
        }
        ProxyChangeListener.setProxyConfig(ip, port, null, pacArray);
    }

    // 埋点统计,只需要tab切换的时候统计
    // 统计不同的url，同一个tab的id
    private void statisticApp(TabFragment tabFragment) {
        UserInfo userInfo = mMainExtraBean.getUserInfo();
        if (userInfo != null) {
            String startUrl = tabFragment.getStartURL();
            if (!TextUtils.isEmpty(startUrl)) {
                String appID = "";
                String appName = "";
                Uri uri = Uri.parse(startUrl);
                if (uri != null) {
                    appID = uri.getQueryParameter(Globals.WEB_APP_ID);
                    appName = uri.getQueryParameter(Globals.WEB_APP_NAME);
                }
                String url = tabFragment.getURLFromAddrBar();
                LogHandlerUtils.savePoint(new PointModel(url, userInfo, appID, appName));
            }
        }
    }

    public CollectionItemData getCollectionData() {
        CollectionItemData collectionItemData = null;
        TabFragment tabFragment = getCurrentFragment();
        if (tabFragment != null) {
            String url = tabFragment.getURLFromAddrBar();
            if (!TextUtils.isEmpty(url)) {
                collectionItemData = new CollectionItemData();
                collectionItemData.url = url;
                collectionItemData.title = getTopWebViewTitle(tabFragment);
                collectionItemData.imageUrl = getTabIcon(tabFragment);
            }
        }
        return collectionItemData;
    }

    //收藏获取当前tab的图标，收藏需要图标
    private String getTabIcon(TabFragment tabFragment) {
        String iconUrl = "";
        String startUrl = tabFragment.getStartURL();
        if (!TextUtils.isEmpty(startUrl)) {
            String parentID = CommonUtils.getUrlParams(startUrl, Globals.WEB_APP_ID);
            if (!TextUtils.isEmpty(parentID)) {
                for (HomeAppsBean homeAppsBean : mMainExtraBean.getHomeApps()) {
                    String appId = homeAppsBean.getAppId();
                    if (!TextUtils.isEmpty(appId) && parentID.equals(appId)) {
                        return homeAppsBean.getAppImgUrl();
                    }
                }
            }
        }
        return iconUrl;
    }

    public TabFragment getCurrentFragment() {
        return (TabFragment) getChildFragmentManager().findFragmentByTag(TabFragment.class.getName());
    }

    public void onBackPressed() {
        if (mFontSizeChangeViewContainer.getVisibility() == View.VISIBLE) {
            mFontSizeChangeViewContainer.setVisibility(View.INVISIBLE);
            return;
        }
        if (mMenuView.getVisibility() == View.GONE) {
            BaseUtil.hideKeyBoard(mContext);
            return;
        }
        if (mMenuFragment.isMoreMenuVisible()) {
            mMenuFragment.hideMoreMenu(true);
            return;
        }
        if (YspPreferences.getInstance().getSharedPreferences().getString("closePageType","").equals("1")) {
            TabManager.getInstance().removeAllViews();
            showHomePage();
            EventBus.getDefault().post(new TabChangeEvent(0));
        } else {
            if (YspPreferences.getInstance().getSharedPreferences().getString("closePageType","").equals("2")){
                YspPreferences.getInstance().getSharedPreferences().edit().putString("closePageType","1").apply();

            }
            browserBack();

        }
    }

    public void browserBack() {
        TabFragment tabFragment = getCurrentFragment();
        if (tabFragment != null) {
            tabFragment.onTabBack();
        } else {
            showHomePage();
        }
    }

    public void showHomePage() {
        TabFragment tabFragment = getCurrentFragment();
        if (tabFragment != null) {
            //回到九宫格之前保存当前tab的快照截图
            tabFragment.getTabAvatarName(true);
        }
        if (mInteractionListener != null) {
            mInteractionListener.showNavigationFragment();
        }
    }

    public void handleApps(String url) {

        //1、判断当前历史中是不是有这个tab，如果有，则先打开历史，再去开启VPN

        //2、历史中没有，先开启VPN，在打开该页面
        if (!isHidden()) {
            //当前已经开启并且就在此tab上
            TabFragment tabFragment = getCurrentFragment();
            if (tabFragment != null && url.equals(tabFragment.getStartURL())) return;
        }

        //先判断list集合的topTab是否存在
        TabFragment tabFragment = mTabManager.getTabFragment(url);
        if (tabFragment != null) {
            attachTabFragment(tabFragment, true);
        } else {
            openNewTab(url, null);
        }
    }

    //获取tabMenu并且创建一个新tab并切换到这个tab,如果是重新进到后台缓存的tab，是不会走这个逻辑
    private void openNewTab(final String url, final DeveloperAppModel developerAppModel) {
        //做SSO的相关请求
        final ManagedSingleSignOn managedSingleSignOn = mMainExtraBean.getManagedSingleSignOn();
        final String companyId = mMainExtraBean.getUserInfo().getCompanyId();
        if (managedSingleSignOn != null) {
            final int interval = managedSingleSignOn.interval;
            showLoading("正在获取SSO配置...");
            Flowable.just(interval).flatMap(new Function<Integer, Publisher<ManagedSingleSignOn>>() {
                @Override
                public Publisher<ManagedSingleSignOn> apply(Integer interval) throws Exception {
                    Flowable<ManagedSingleSignOn> flowable;
                    switch (interval) {
                        case -1:
                            flowable = HttpMethods.getInstance().ssoFlowable(companyId, mUserName, mPassword);
                            break;
                        case 0:
                            flowable = Flowable.just(managedSingleSignOn);
                            break;
                        default:
                            long startTime = EnterConfig.getInstance().getSSOFetchStartTimeStamp();
                            final long currentTime = System.currentTimeMillis();
                            if (startTime > 0 && currentTime - startTime > interval * 1000) {
                                flowable = HttpMethods.getInstance().ssoFlowable(companyId, mUserName, mPassword).flatMap(new Function<ManagedSingleSignOn, Publisher<ManagedSingleSignOn>>() {
                                    @Override
                                    public Publisher<ManagedSingleSignOn> apply(ManagedSingleSignOn managedSingleSignOn) throws Exception {
                                        EnterConfig.getInstance().setSSOConfigFetchStartTimeStamp(currentTime);
                                        return Flowable.just(managedSingleSignOn);
                                    }
                                });
                            } else {
                                flowable = Flowable.just(managedSingleSignOn);
                            }
                            break;
                    }
                    return flowable;
                }
            }).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<ManagedSingleSignOn>() {
                @Override
                public void accept(ManagedSingleSignOn managedSingleSignOn) throws Exception {
                    hideLoading();
                    mMainExtraBean.setManagedSingleSignOn(managedSingleSignOn);
                    createTab(url, developerAppModel);
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    hideLoading();
                    String msg = throwable.getMessage();
                    ToastUtils.showToast("SSO配置获取失败,错误信息：" + msg);
                    createTab(url, developerAppModel);
                }
            });
        } else {
            createTab(url, developerAppModel);
        }
    }

    private void createTab(String url, DeveloperAppModel developerAppModel) {
        TabFragment.Builder builder = new TabFragment.Builder().setUrl(url);
        //设置二级菜单内容
        String menu = optAppMenu(url);
        if (!TextUtils.isEmpty(menu)) {
            builder.setAppMenu(menu);
        }
        //设置文档预览
        FilePreviewConfig filePreviewConfig = null;
        Company.DocSetting docSetting = mMainExtraBean.getDocSetting();
        int doc = docSetting.documentSecurity;
        boolean highSpeed = docSetting.highSpeedMode;
        String filePreviewServer = docSetting.serverAddress;
        switch (doc) {
            case 1:
                filePreviewConfig = new FilePreviewConfig.Builder().setDocConvertServer(DOC_CONVERT_SERVER_URL).setType(highSpeed ? TYPE_ONLINE_PREVIEW : TYPE_MOBILE_DOWNLOAD_PREVIEW).build();
                break;
            case 2:
                filePreviewConfig = new FilePreviewConfig.Builder().setDocConvertServer(filePreviewServer).setType(highSpeed ? TYPE_ONLINE_PREVIEW : TYPE_MOBILE_DOWNLOAD_PREVIEW).build();
                break;
            default:
                break;
        }
        builder.setFilePreview(filePreviewConfig);

        //设置sso
        initTabSSO(url, builder);
        //设置是否开启了调试模式
        SharedPreferences preferences = YspPreferences.getInstance().getSharedPreferences();
        boolean debug = preferences.getBoolean(Globals.YSP_DEBUG, false);
        builder.setDebugMode(debug);
        //设置全局运行时
        String globalRTVersion = debug ? preferences.getString(Globals.RT_GLOBAL_VERSION, "") : "";
        builder.setGlobalRuntime(globalRTVersion);
        //设置是否开启双WebView
        boolean open2WebView = preferences.getBoolean(Globals.YSP_DEBUG_WEB_VIEW_MODE, true);
        builder.setDefault2WebView(open2WebView);
        //设置是否是扫码打开适配应用
        if (developerAppModel != null) {
            builder.setDeveloperAppModel(developerAppModel);
        }
        //设置字体大小
        int textZoom = BaseUtil.parseTextZoomSize(preferences.getInt(Globals.WEB_VIEW_TEXT_ZOOM, 1));
        builder.setTextZoom(textZoom);
        //设置401认证的配置信息,AD认证，域控等
        ArrayList<HttpAuthModel> httpAuthModels = optHttpAuthModels();
        if (httpAuthModels != null) {
            builder.setHttpAuthorizations(httpAuthModels);
        }
        //设置水印
        WaterMarkSettings waterMarkSettings = EnterConfig.getInstance().getWaterMarkSettings();
        if (waterMarkSettings != null && waterMarkSettings.getType() == 1) {
            WaterMarkConfig waterMarkConfig = waterMarkSettings.getWaterMarkConfig();
            builder.setWaterMark(waterMarkConfig);
        }
        TabFragment tabFragment = builder.build();
        tabFragment.addJavascriptInterface(newCheckInJSModel(url), "yspCheckIn");  //给XWalkView注入其他需要的java原生对象，方便js调用
        configProxy(url);
        attachTabFragment(tabFragment, false);
        mTabManager.addView(tabFragment);
        EventBus.getDefault().post(new YspEvent.UpdateTabCount());

    }

    private String callBack;
    private CheckInJSModel newCheckInJSModel(String url) {
        return new CheckInJSModel(url) {
            /**
             * 移动签到获取当前位置
             */
            @org.xwalk.core.JavascriptInterface
            @JavascriptInterface
            public void locationBegin() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        startLocation();
                    }
                });
            }

            /**
             * 移动签获取照片
             */
            @org.xwalk.core.JavascriptInterface
            @JavascriptInterface
            public void openCamera() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        startCamera();
                    }
                });
            }

            //移动签到获取签到地址
            @org.xwalk.core.JavascriptInterface
            @JavascriptInterface
            public String checkInServerAddress() {
                String server = "";
                Uri uri = Uri.parse(url);
                if (uri != null) {
                    String schema = uri.getScheme();
                    String host = uri.getHost();
                    int port = uri.getPort();
                    server = schema + "://" + host + (port == -1 ? "" : ":" + port);
                }
                return server;
            }

            //二维码扫码
            @org.xwalk.core.JavascriptInterface
            @JavascriptInterface
            public void scan(String callBack) {
                BrowserFragment.this.callBack = callBack;
                if (BaseUtil.isCameraAvailable()) {
                    Intent intent = new Intent(getActivity(), CaptureActivity.class);
                    intent.putExtra(INTENT_QR_SCAN_SERVICE,"1");
                    startActivityForResult(intent, REQUEST_CODE_SCAN);
                } else {
                    ToastUtils.showToast(R.string.camera_permission_request);
                }
            }

            @org.xwalk.core.JavascriptInterface
            @JavascriptInterface
            public void closePage() {
                Message msg = new Message();
                msg.what = 1;
                handler.sendMessage(msg);


            }
            @org.xwalk.core.JavascriptInterface
            @JavascriptInterface
            public void closePageType(String type) {
                YspPreferences.getInstance().getSharedPreferences().edit().putString("closePageType",type).apply();

            }

            @org.xwalk.core.JavascriptInterface
            @JavascriptInterface
            public void closePageMoney() {
                handler.sendEmptyMessage(2);
            }
        };


    }
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    Log.e("fff","ddd");
                    TabManager.getInstance().removeAllViews();
                    showHomePage();
                    EventBus.getDefault().post(new TabChangeEvent(0));
                    break;
                case 2:
                    goBack();
                    break;
            }
        }
    };


    //设置单点登录相关
    private void initTabSSO(String url, TabFragment.Builder builder) {
        ManagedSingleSignOn managedSingleSignOn = mMainExtraBean.getManagedSingleSignOn();
        if (managedSingleSignOn != null) {
            String type = managedSingleSignOn.sendTokenPosition;
            if ("cookie".equalsIgnoreCase(type)) {
                String ssoValue = managedSingleSignOn.singleSignOn;
                ManagedSingleSignOn.Cookie cookie = managedSingleSignOn.cookie;
                if (!TextUtils.isEmpty(ssoValue) && cookie != null) {
                    String cookieStr = cookie.name + "=" + ssoValue + ";Path=" + cookie.path + ";Domain=" + cookie.domain + (cookie.secure ? ";SECURE" : "");
                    ArrayList<CookieModel> cookieModels = new ArrayList<>();
                    CookieModel cookieModel = new CookieModel(url, cookieStr);
                    cookieModels.add(cookieModel);
                    builder.setCookies(cookieModels);
                }
            } else {
                List<ManagedSingleSignOn.SSOToken> ssoTokens = managedSingleSignOn.ssoTokens;
                if (ssoTokens != null && ssoTokens.size() > 0) {
                    if ("url".equalsIgnoreCase(type)) {
                        ArrayList<UrlTokenSSOModel> urlTokenSSOModels = new ArrayList<>();
                        for (ManagedSingleSignOn.SSOToken ssoToken : ssoTokens) {
                            String host = CommonUtils.getHost(ssoToken.address);
                            String params = ssoToken.parameters;
                            UrlTokenSSOModel urlTokenSSOModel = new UrlTokenSSOModel(host, params);
                            urlTokenSSOModels.add(urlTokenSSOModel);
                        }
                        builder.setUrlTokenSSO(urlTokenSSOModels);
                    } else if ("header".equalsIgnoreCase(type)) {
                        ArrayList<RequestHeaderSSOModel> requestHeaderSSOModels = new ArrayList<>();
                        for (ManagedSingleSignOn.SSOToken ssoToken : ssoTokens) {
                            String host = CommonUtils.getHost(ssoToken.address);
                            String params = ssoToken.parameters;
                            int index = params.indexOf(":");
                            if (index != -1) {
                                String[] ps = params.split(":");
                                HashMap<String, String> hashMap = new HashMap<>();
                                hashMap.put(ps[0], ps[1]);
                                RequestHeaderSSOModel requestHeaderSSOModel = new RequestHeaderSSOModel(host, hashMap);
                                requestHeaderSSOModels.add(requestHeaderSSOModel);
                            }
                        }
                        builder.setRequestHeaderSSO(requestHeaderSSOModels);
                    }
                }
            }
        }
    }

    //获取当前url的二级菜单内容，只有enterplorer协议才有
    private String optAppMenu(String url) {
        String menu = "";
        if (url.startsWith("enterplorer://")) {
            String id = CommonUtils.getUrlParams(url, Globals.WEB_APP_ID);
            List<HomeAppsBean> mHomeApps = mMainExtraBean.getHomeApps();
            if (mHomeApps != null && mHomeApps.size() > 0) {
                for (HomeAppsBean homeAppsBean : mHomeApps) {
                    if (homeAppsBean.getAppId().equals(id)) {
                        List<HomeAppsBean> homeAppsBeans = homeAppsBean.getHomeAppsBeans();
                        if (homeAppsBeans != null) {
                            menu = new Gson().toJson(homeAppsBeans);
                        }
                    }
                }
            }
        }
        return menu;
    }

    //获取http请求认证的models
    private ArrayList<HttpAuthModel> optHttpAuthModels() {
        String uuid = mMainExtraBean.getUserInfo().getUuid();
        String key = Aes.generateKey(uuid);
        XCloudSignDao xCloudSignDao = EnterDbManager.getInstances().getXCloudSignDao();
        List<XCloudSign> xCloudSigns = xCloudSignDao.queryBuilder().list();
        if (xCloudSigns != null && !TextUtils.isEmpty(key)) {
            ArrayList<HttpAuthModel> httpAuthModels = new ArrayList<>();
            for (XCloudSign xCloudSign : xCloudSigns) {
                String type = xCloudSign.getExtra1();
                if (!TextUtils.isEmpty(type) && "1".equals(type)) {
                    String host = xCloudSign.getHost();
                    String userName = EncUtils.decrypt(key, xCloudSign.getUserName());
                    String password = EncUtils.decrypt(key, xCloudSign.getPassword());
                    if (!TextUtils.isEmpty(host) && !TextUtils.isEmpty(userName) && !TextUtils.isEmpty(password)) {
                        httpAuthModels.add(new HttpAuthModel(host, userName, password));
                    }
                }
            }
            if (httpAuthModels.size() > 0) {
                return httpAuthModels;
            }
        }
        return null;
    }

    public void addNewDeveloperTab(String result) {
        try {
            JSONObject jsonObject = new JSONObject(result);
            String url = jsonObject.optString("url");
            DeveloperAppModel developerAppModel = new DeveloperAppModel(url, jsonObject.optString("app"), jsonObject.optString("runtime"));
            openNewTab(url, developerAppModel);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //浏览器移动签到定位
    private void startLocation() {
        final WaitDialog waitDialog = new WaitDialog(mContext);
        waitDialog.setMessage("定位中...");
        waitDialog.show();

        final AMapLocationClient aMapLocationClient = new AMapLocationClient(mContext.getApplicationContext());
        aMapLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                    String address = aMapLocation.getAddress();
                    TabFragment tabFragment = getCurrentFragment();
                    if (tabFragment != null) {
                        String uuid = mMainExtraBean.getUserInfo().getUuid();
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("uuid", uuid);
                            jsonObject.put("address", address);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        tabFragment.loadJSApi("javascript: setLocation(" + jsonObject + ");");
                    }
                } else {
                    ToastUtils.showToast("定位失败");
                }
                waitDialog.dismiss();
                aMapLocationClient.onDestroy();
            }
        });
        AMapLocationClientOption aMapLocationClientOption = new AMapLocationClientOption();
        aMapLocationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        aMapLocationClientOption.setOnceLocation(true);
        aMapLocationClientOption.setHttpTimeOut(20000);
        aMapLocationClient.setLocationOption(aMapLocationClientOption);
        aMapLocationClient.startLocation();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        WPSManager.getInstance().unBindWPS(mContext);
    }

    private File mTempFile;

    //浏览器移动签到拍照
    private void startCamera() {
        String fileName = System.currentTimeMillis() + ".jpg";
        mTempFile = new File(FileUtils.getEnterImgCachePath(), fileName);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTempFile));
        startActivityForResult(intent, REQUEST_CODE_SEND_IMAGE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case  REQUEST_CODE_SEND_IMAGE:
                if (requestCode == REQUEST_CODE_SEND_IMAGE && mTempFile != null && mTempFile.exists()) {
                    //服务端只需要640*640的图片
                    BitmapFactory.Options newOpts = new BitmapFactory.Options();
                    newOpts.inJustDecodeBounds = true;
                    Bitmap bitmap = BitmapFactory.decodeFile(mTempFile.getAbsolutePath(), newOpts);
                    int w = newOpts.outWidth;
                    int h = newOpts.outHeight;
                    int be = 1;
                    if (w > h && w > 640) {
                        be = newOpts.outWidth / 640;
                    } else if (w < h && h > 640) {
                        be = newOpts.outHeight / 640;
                    }
                    if (be <= 0)
                        be = 1;
                    newOpts.inSampleSize = be;
                    newOpts.inJustDecodeBounds = false;
                    bitmap = BitmapFactory.decodeFile(mTempFile.getAbsolutePath(), newOpts);
                    byte[] bytes = FileUtils.compressImage(bitmap);
                    String result = Base64.encodeToString(bytes, Base64.DEFAULT);
                    TabFragment tabFragment = getCurrentFragment();
                    if (tabFragment != null && !TextUtils.isEmpty(result)) {
                        tabFragment.loadJSApi("javascript: setImageData('" + result + "');");
                    }
                    boolean b = mTempFile.delete();
                }
                break;
            case REQUEST_CODE_SCAN:
               String result =  data.getStringExtra(INTENT_QR_SCAN_RESULT);
                if(!TextUtils.isEmpty(result) && !TextUtils.isEmpty(callBack)){
                    TabFragment tabFragment = getCurrentFragment();
                    if (tabFragment != null && !TextUtils.isEmpty(result)) {
                        tabFragment.loadJSApi("javascript: "+callBack+"('" + result + "');");
                    }
                }else{
                    ToastUtils.showToast("扫码失败");
                }
                break;
        }

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden) {
            final FragmentManager fragmentManager = getChildFragmentManager();
            final Fragment fragment = fragmentManager.findFragmentById(R.id.fl_browser_content);
            if (fragment != null) {
                fragmentManager.beginTransaction().remove(fragment).commit();
                fragmentManager.executePendingTransactions();
            }
        }
    }

    //tab历史的点击事件
    public void onTabHistoryItemClick(boolean isClose, int position) {
        if (position == 0) {
            showHomePage();
            mInteractionListener.closeDrawers();
        } else {
            position -= 1;
            if (isClose) {
                //删除其他位置上的tab
                TabFragment tabFragment = getCurrentFragment();
                TabFragment clickTabFragment = mTabManager.getFragment(position);
                if (tabFragment != null && clickTabFragment != null) {
                    if (tabFragment == clickTabFragment) {
                        int next = mTabManager.removeView(position);
                        if (next != -1) {
                            TabFragment nextTabFragment = mTabManager.getFragment(next);
                            if (nextTabFragment != null) {
                                attachTabFragment(nextTabFragment, true);
                                mInteractionListener.refreshTabDrawer(next + 1);
                            } else {
                                showHomePage();
                                mInteractionListener.closeDrawers();
                                mInteractionListener.refreshTabDrawer(0);
                            }
                        } else {
                            showHomePage();
                            mInteractionListener.closeDrawers();
                            mInteractionListener.refreshTabDrawer(0);
                        }
                    } else {
                        mTabManager.removeView(position);
                        TabFragment tab = getCurrentFragment();
                        if (tab != null) {
                            mInteractionListener.refreshTabDrawer(mTabManager.getTabPosition(tab.getStartURL()) + 1);
                        }
                    }
                }
            } else {
                TabFragment tabFragment = getCurrentFragment();
                TabFragment clickTab = mTabManager.getFragment(position);
                if (tabFragment != null && clickTab != null && tabFragment != clickTab) {
                    attachTabFragment(clickTab, true);
                }
                mInteractionListener.closeDrawers();
            }
        }
    }

    @Override
    public void backTop() {
        showHomePage();
    }

    /**
     * WebView地址栏地址变化，以前是统计所有url
     */
    @Override
    public void webViewUrlChanged(String url) {

    }

    @SuppressLint("CommitPrefEdits")
    @Override
    public boolean onReceivedHttpAuthRequest(XWalkView view, final XWalkHttpAuthHandler handler, final String host, String realm) {
        String title = (!TextUtils.isEmpty(realm) ? "位于" + realm + "的" : "") + "服务器" + host + "要求用户名和密码";
        DialogHelper.showHttpAuthRequest(view.getContext(), title, new VPNLoginRequest() {
            @Override
            public void loginRequest(String userName, String password) {
                handler.proceed(userName, password);
                int len = mTabManager.getSize();
                for (int i = 0; i < len; i++) {
                    TabFragment tabFragment = mTabManager.getFragment(i);
                    if (tabFragment != null) {
                        tabFragment.notifyHttpAuthDataChanged(host, userName, password);
                    }
                }
            }

            @Override
            public void errorData() {
                handler.cancel();
            }
        });
        return true;
    }

    @Override
    public void tabProgressChanged(int progress) {
        if (progress == 0 || progress == 100) {
            mProgressBar.setProgress(0);
            mProgressBar.setVisibility(View.GONE);
        } else {
            mProgressBar.setVisibility(View.VISIBLE);
            mProgressBar.setProgress(progress);
        }
    }

    @Override
    public void backPreWebView(boolean isFromCloseWindow) {
    }

    @Override
    public boolean shouldHandleNoMatcherUrlFromOpenWindow(String url) {
        return false;
    }

    @Override
    public boolean shouldInterceptWebViewShouldOverrideUrlLoadingMethod(XWalkView view, String url) {
        return false;
    }

    //该方法在非ui线程执行：///获取密码代填的用户名密码的配置信息
    @Override
    public AutoLoginModel getAutoLoginModel(String url) {
        String host = CommonUtils.getHost(url);
        if (TextUtils.isEmpty(host)) {
            return null;
        }
        XPs xPs = mXPsMap.get(host);
        if (xPs == null) {
            return null;
        }
        String userNameXPath = xPs.getUXPath();
        if (TextUtils.isEmpty(userNameXPath)) {
            return null;
        }
        String passwordXPath = xPs.getPXPath();
        if (TextUtils.isEmpty(passwordXPath)) {
            return null;
        }
        String submitXPath = xPs.getBXPath();
        if (TextUtils.isEmpty(submitXPath)) {
            return null;
        }
        Log.e("Properties",host);
        XCloudSignDao dao = EnterDbManager.getInstances().getXCloudSignDao();
        XCloudSign xCloudSign = dao.queryBuilder().where(XCloudSignDao.Properties.Host.eq(host)).build().unique();
        if (xCloudSign != null) {
            String encUserName = xCloudSign.getUserName();
            String encPassword = xCloudSign.getPassword();
            String uuid = mMainExtraBean.getUserInfo().getUuid();
            if (!TextUtils.isEmpty(encUserName) && !TextUtils.isEmpty(encPassword) && !TextUtils.isEmpty(uuid)) {
                String userName = EncUtils.decrypt(uuid, encUserName);
                String password = EncUtils.decrypt(uuid, encPassword);
                if (!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(password)) {
                    return new AutoLoginModel(userNameXPath, passwordXPath, submitXPath, userName, password);
                }
            }
        }
        return null;
    }

    @Override
    public void filePreviewConvertResult(String url) {

    }

    @Override
    public boolean showAdapterLoading(String message) {
        return false;
    }

    @Override
    public boolean hideAdapterLoading() {
        return false;
    }

    public void hideExtraMenu() {
        mMenuFragment.hideExtraMenu();
    }

    public interface VPNLoginRequest {
        void loginRequest(String userName, String password);

        void errorData();
    }

    public interface BrowserInteractionListener {
        void closeDrawers();

        void refreshTabDrawer(int position);

        void showNavigationFragment();
    }

    //setThirdPartyApp()
}
